close all
clear all
clc

Eng=13.474;
lambda=0.9201;
Attl=4854.22e4; % Attenuation length in unit of Angstrom for water @ 13.474 keV
mu=1/Attl;
beta=mu*lambda/4/pi;

I0=1e4;  

Fluores_DB_Qz_file={
    'sph01_scan329_DB_EL.txt';     % bar 3  SPM/KCl/FeCl3 pH 4
    'sph02_scan406_DB_EL.txt';     % bar 3 KCl 100 mM, FeCl3 5 mM
    }

qz=[0.01:0.001:0.035]';
for k=1:length(Fluores_DB_Qz_file)
    data=dlmread(Fluores_DB_Qz_file{k});
    DBEL{k}.Intensity=data(:,2);
    DBEL{k}.Intensity_err=data(:,3);
end

%%
close all
clc
MarkerType={'o','s','v','^','d','>','<'}
COLOR={'k','r','b',[0 0.4 0],'m','k','k'}

figure
hold on
for k=1:length(Fluores_DB_Qz_file)
    DBEL_corr{k}.Intensity=I0*DBEL{k}.Intensity;
    DBEL_corr{k}.Intensity_err=I0*DBEL{k}.Intensity_err;
    H=ploterr(qz,DBEL_corr{k}.Intensity,[],DBEL_corr{k}.Intensity_err,MarkerType{k},'hhy',0.1);
    set(H,'LineWidth',3,'color',COLOR{k})
end
%%
Param=[
    1, 0.0218, 0;
    ]
LB=[0, 0.021,  0 ];
UB=[1, 0.023, 1 ];

close all
clc

figure
hold on
xfit=(0.01:0.0001:0.0350)';
qmax=21;
for k=1:length(Fluores_DB_Qz_file)
    x=qz;
    y=DBEL_corr{k}.Intensity;
    yerr=DBEL_corr{k}.Intensity_err;
    
    xdata=x(1:qmax);
    ydata=y(1:qmax);
    ydata_err=yerr(1:qmax);
    
    
    
    [p_opt{k}]=optim_fitsubphase(Param,xdata,ydata,ydata_err,LB,UB)
    
    C=p_opt{k}(1);
    qc=p_opt{k}(2);
    bkg=p_opt{k}(3);
    
    T=Transmission(xfit,p_opt{k}(2),beta,lambda);
    D=fitsubphase(xfit,p_opt{k}(2),Eng, Attl);    
    yfit{k}=C*T.*D+bkg;
    H=ploterr(x,y,[],yerr,MarkerType{k},'hhy',0.1);
    set(H,'color',COLOR{k},'LineWidth',3,'MarkerSize',8);
    plot(xfit,yfit{k},'-','LineWidth',3,'color',COLOR{k});
end
set(gca,'yscale','log');

